package com.example.springboot01;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;

public class SshShellUtil {

    public static void execCommand(String ip, int port, String username, String password, String command) {
        Connection conn = new Connection(ip, port);
        Session sess = null;
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);
            if (isAuthenticated) {
                sess = conn.openSession();
                sess.execCommand(command);
                InputStream is = new StreamGobbler(sess.getStdout());
                BufferedReader brs = new BufferedReader(new InputStreamReader(is));
                while (true) {
                    String line = brs.readLine();
                    if (line == null) {
                        break;
                    }
                    System.out.println(line);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (Objects.nonNull(sess)) {
                sess.close();
            }
            conn.close();
        }
    }

    public static void main(String[] args) {
        execCommand(Constant.IP, Constant.PORT, Constant.USER, Constant.PASS, "ls");
    }
}
